package servlet.admin;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import entity.Pages;
import service.admin.BorrowListService;
import service.admin.impl.BorrowListServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * BorrowListServlet
 *
 * @author lenovo
 * @since 2023/9/5
 */
@WebServlet("/admin/borrowList")
public class BorrowListServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    //引入服务层
    BorrowListService service = new BorrowListServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json; charset=utf8");
        // 接收参数
        String limit = req.getParameter("limit");
        String page = req.getParameter("page");
        String condition = (String) req.getParameter("condition");
        String conditionValue = (String) req.getParameter("conditionValue");
        if(page == null) {
            page = "1";
        }
        if(limit == null) {
            limit = "10";
        }
        int code = 1;
        String msg = "error";
        int count = 0;

        //创建分页对象
        Pages pages = new Pages();
        pages.setPageSize(Integer.valueOf(page));
        pages.setPageCountNo(Integer.valueOf(page));
        count = service.total(condition,conditionValue);
        pages.setPageCount(count);

        JSONArray array = service.getList(condition,conditionValue,pages);

        if (!array.isEmpty()){
            code = 0;
            msg = "有数据";
        }

        JSONObject json = new JSONObject();

        json.put("code",code);
        json.put("count",count);
        json.put("msg",msg);
        json.put("data",array.toArray());

        PrintWriter out = resp.getWriter();

        out.print(json.toJSONString());
        out.flush();
        out.close();
    }
}
